package com.ellfors.module_first.picture_selector

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.ellfors.common.base.BaseActivity
import com.ellfors.common.base.EmptyViewModel
import com.ellfors.common.ext.loadImageCustom
import com.ellfors.common.ext.toast
import com.ellfors.module_first.databinding.ActivityPictureSelectorBinding


/**
 * 选择图片
 */
class PictureSelectorActivity : BaseActivity<ActivityPictureSelectorBinding, EmptyViewModel>() {

    private val pickVisualMediaLauncher = registerForActivityResult(
        ActivityResultContracts.PickVisualMedia()
    ) { uri: Uri? ->
        uri?.let {
            // 处理选定的媒体 URI
            handlePickedMedia(it)
        } ?: run {
            // 用户取消选择
            "没有选择媒体".toast()
        }
    }

    companion object {
        fun start(activity: AppCompatActivity) {
            Intent(activity, PictureSelectorActivity::class.java).apply {
                activity.startActivity(this)
            }
        }
    }

    override fun initView() {
        showTitleBar("Picture Selector")

        mBinding.btnSelectPicture.setOnClickListener {
            pickVisualMediaLauncher.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
        }
    }

    override fun initData() {

    }

    @SuppressLint("CheckResult")
    private fun handlePickedMedia(uri: Uri) {
        val file = PictureSelectorUtils.uriToFile(this, uri)
        file?.let {
            mBinding.ivPicture.loadImageCustom(file.absolutePath) {
                centerCrop()
            }
        } ?: let {
            "获取路径失败".toast()
        }
    }
}